package com.common.util;

import com.zhao.model.MailModel;

import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendEmailUtil {

    public static boolean mailSend(MailModel mailModel){
        try {
            Properties props = new Properties();
            props.put("mail.smtp.auth","true");
            props.put("mail.smtp.host",mailModel.getHost());
            props.put("mail.smtp.port",25);
            props.put("mail.smtp.starttls.enable","true");
            //创建会话
            VerifyMail verifyMail = new VerifyMail(mailModel.getUsername(),mailModel.getPassword());
            Session mailSession = Session.getInstance(props,verifyMail);
            //mailSession.setDebug(true);
            //创建信息对象
            Message message = new MimeMessage(mailSession);
            //发送者
            InternetAddress fromAddress = new InternetAddress(mailModel.getFromAddress());
            //接收者
            InternetAddress toAddress = new InternetAddress(mailModel.getToAddress());
            message.setFrom(fromAddress);//设置邮件来源
            message.setRecipient(MimeMessage.RecipientType.TO,toAddress);//设置邮件接收者
            message.setSubject(mailModel.getSubject());
            message.setSentDate(new Date());
            message.setContent(mailModel.getContent(),mailModel.getContentType());
            message.saveChanges();
            Transport trans = mailSession.getTransport("smtp");
            trans.connect(mailModel.getHost(),mailModel.getUsername(),mailModel.getPassword());
            System.out.println(trans);
            trans.sendMessage(message,message.getAllRecipients());
            return true;
        }catch (Exception e){
            System.out.println(e.getMessage());
            return  false;
        }
    }

    public static void main(String[] args) {
        MailModel mailModel = new MailModel();
        mailModel.setHost("smtp.exmail.qq.com");
        mailModel.setPort(465);
        mailModel.setUsername("huizhixin@xyebank.com");//
        mailModel.setPassword("Huizhixin2016");
        mailModel.setFromAddress("huizhixin@xyebank.com");
        mailModel.setToAddress("742834720@qq.com");
        mailModel.setSubject("执行结果");
        mailModel.setContent("test mail");
        mailModel.setContentType("text/html;charset=utf-8");
        System.out.println(mailModel.toString());
        System.out.println(mailSend(mailModel));
    }
}
